package com.thermoberg.passport.controllor;

import com.thermoberg.passport.entity.SbyPassport;
import com.thermoberg.passport.service.SbyPassportService;
import com.thermoberg.passport.util.BackstargeToken;
import com.thermoberg.passport.util.LoginToken;
import com.thermoberg.passport.util.OptimizeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * Created by wanghe on 2016/11/2.
 */
@Controller
@RequestMapping(value = "/account")
public class LoginController {
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    private final String FAIL_USER = "{\"code\": 2, \"msg\": \"用户名密码错误！\"}";
    private final String RETURN_SUCCESS = "{\"code\": 0, \"url\": \"personal/infomation\"}";

    @Autowired
    private LoginToken loginToken;

    @Autowired
    private BackstargeToken backstargeToken;

    @Autowired
    private OptimizeToken optimizeToken;

    @Autowired
    private SbyPassportService sbyPassportService;

    @RequestMapping(value = "/login")
    public String LoginUser(@RequestParam(required = false) String redirectUrl, ModelMap model,HttpServletRequest request) {
            try {
                String chat=request.getParameter("chat");
                String backUrl=request.getParameter("redirectUrl");
                String url = java.net.URLDecoder.decode(redirectUrl, "utf-8");
                model.addAttribute("chat", chat);
                model.addAttribute("backUrl", backUrl);
                model.addAttribute("redirectUrl", url);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        return "login";
    }

    @RequestMapping(value = "/doLogin",method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public @ResponseBody
    String login(@RequestParam String userName,
                 @RequestParam String passWord,@RequestParam String chat,HttpServletResponse response) {
        SbyPassport sbyPassport = sbyPassportService.loginuser(userName,passWord,chat);
        if(sbyPassport != null){
            if(chat.equals("backstagetoken")){
                sendbackstargeCookie(response, sbyPassport.getUsername(), "0", sbyPassport.getSmsManager().getIsFinance());
            }
            if(chat.equals("optimizetoken")){
                sendoptimizeCookie(response,sbyPassport.getUsername());
            }
            sendCookie(response, sbyPassport.getId(), sbyPassport.getUsername(), sbyPassport.getUserrole());
            return RETURN_SUCCESS;
        }
        return FAIL_USER;
    }

    @RequestMapping(value = "/dologout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        response.addCookie(eraseCookie("token"));
        return "login";
    }

    public void sendCookie(HttpServletResponse response, Integer id, String username, Integer userrole) {
        String token = loginToken.buildToken(id, username, userrole);
        logger.debug("loginToken" + token);
        response.addCookie(buildCookie("logintoken",token));
    }

    public Cookie buildCookie(String name,String token) {
        Cookie cookie = new Cookie(name, token);
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        return cookie;
    }

    public void sendbackstargeCookie(HttpServletResponse response, String username, String branchId, Integer isFinance) {
        String token = backstargeToken.buildToken(username, branchId, isFinance);
        logger.info("Token" + token);
        response.addCookie(buildbackstargeCookie("token",token));
    }

    public Cookie buildbackstargeCookie(String name,String token) {
        Cookie cookie = new Cookie(name, token);
        cookie.setMaxAge(60 * 60 * 2);
        cookie.setPath("/");
        return cookie;
    }

    public void sendoptimizeCookie(HttpServletResponse response, String username) {
        String token = optimizeToken.buildToken(username);
        logger.info("optimizeToken" + token);
        response.addCookie(buildoptimizeCookie("optimizetoken",token));
    }

    public Cookie buildoptimizeCookie(String name,String token) {
        Cookie cookie = new Cookie(name, token);
        cookie.setMaxAge(60 * 60 * 2);
        cookie.setPath("/");
        return cookie;
    }

    public Cookie eraseCookie(String name) {
        Cookie cookie = new Cookie(name, "");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        return cookie;
    }
}
